package com.lehecai.core.task.dispatcher;

import com.lehecai.core.task.entity.AsyncTaskItem;
import com.lehecai.core.task.service.IQueueService;
import com.lehecai.core.task.type.AsyncTaskType;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by qatang on 14-3-27.
 */
public abstract class AbstractAsyncTaskSenderDispatcher implements IAsyncTaskSenderDispatcher {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Map<AsyncTaskType, IQueueService> QUEUE_MAP = new HashMap<AsyncTaskType, IQueueService>();

    @Override
    public boolean dispatch(AsyncTaskItem asyncTaskItem) throws Exception {
        if (asyncTaskItem == null || asyncTaskItem.getAsyncTask() == null) {
            throw new Exception("异步任务接收队列分发器分发失败：asyncTaskItem及其asyncTask属性参数不能为空");
        }
        AsyncTaskType asyncTaskType = asyncTaskItem.getAsyncTask().getAsyncTaskType();
        if (QUEUE_MAP == null) {
            throw new Exception("异步任务接收队列分发器分发失败：队列map不能为空");
        }
        IQueueService queueService = QUEUE_MAP.get(asyncTaskType);
        if (queueService == null) {
            throw new Exception("异步任务接收队列分发器分发失败：queueService不能为空");
        }

        String queueName = generateQueueName(asyncTaskItem);
        if (StringUtils.isEmpty(queueName)) {
            throw new Exception("异步任务接收队列分发器分发失败：queueName不能为空");
        }

        return queueService.push(queueName, asyncTaskItem);
    }

    protected abstract String generateQueueName(AsyncTaskItem asyncTaskItem);

    public Map<AsyncTaskType, IQueueService> getQUEUE_MAP() {
        return QUEUE_MAP;
    }

    public void setQUEUE_MAP(Map<AsyncTaskType, IQueueService> QUEUE_MAP) {
        this.QUEUE_MAP = QUEUE_MAP;
    }
}
